import { getCurrentApp, Hook, VueService } from 'vue3-oop'
import type { Router, RouteRecordRaw } from 'vue-router'
import { createRouter, createWebHashHistory } from 'vue-router'
import {Injectable} from "injection-js";
import {routes} from "./routes";

@Injectable()
export default class RouterService extends VueService {
  history = createWebHashHistory()
  router!: Router
  app = getCurrentApp()!

  static instCount = 0;

  constructor() {
    super();
    RouterService.instCount++>1 && console.error("RouterService.instCount="+RouterService.instCount)
  }

  // 为了解决热更新循环引用,采用函数传参初始化
  initRoutes(routes: RouteRecordRaw[]) {
    this.router = createRouter({
      history: this.history,
      routes,
    })
    this.app.use(this.router)
    window.$router = this.router;
  }

  @Hook('BeforeUnmount')
  unmount() {
    this.history.destroy()
  }

  get currentRoute() {
    return this.router.currentRoute.value
  }

  get routes(){
    return routes;
  }
}

@Injectable()
export class RouterInit {
  constructor(private routerService: RouterService) {
    routerService.initRoutes(routes)
  }
}

